<!-- 文章编辑弹窗 -->
<template>
  <ele-modal
    :width="1280"
    :visible="visible"
    :confirm-loading="loading"
    :title="isUpdate ? '修改内容' : '新建内容'"
    :body-style="{ paddingBottom: '8px' }"
    @update:visible="updateVisible"
    @ok="save"
  >
    <a-form
      ref="formRef"
      :model="form"
      :rules="rules"
      :label-col="styleResponsive ? { md: 7, sm: 24 } : { flex: '90px' }"
      :wrapper-col="styleResponsive ? { md: 17, sm: 24 } : { flex: '1' }"
    >
      <a-row :gutter="16">
        <a-col :span="12">
          <a-form-item
            label="文章标题"
            name="title"
            :label-col="{ flex: '90px' }"
            :wrapper-col="{ flex: 1 }"
          >
            <a-input
              style="width: 100%"
              allow-clear
              placeholder="请输入文章标题"
              v-model:value="form.title"
            />
          </a-form-item>

          <a-row :gutter="16">
            <a-col
              v-bind="
                styleResponsive ? { md: 12, sm: 24, xs: 24 } : { span: 12 }
              "
            >
              <a-form-item label="所属栏目">
                <cate-select
                  :data="cateList"
                  placeholder="请选择所属栏目"
                  v-model:value="form.cateId"
                />
              </a-form-item>
              <a-form-item
                v-if="form.type === 1"
                label="内容来源"
                name="origin"
              >
                <a-input
                  allow-clear
                  placeholder="请输入内容来源"
                  v-model:value="form.origin"
                />
              </a-form-item>
              <a-form-item v-if="form.type !== 1" label="发布者" name="user">
                <a-input
                  allow-clear
                  :maxlength="20"
                  placeholder="请输入发布者"
                  v-model:value="form.user"
                />
              </a-form-item>
            </a-col>
            <a-col
              v-bind="
                styleResponsive ? { md: 12, sm: 24, xs: 24 } : { span: 12 }
              "
            >
              <a-form-item label="文章模板" :wrapper-col="{ flex: 1 }">
                <a-input
                  allow-clear
                  :disabled="form.type !== 0"
                  placeholder="请输入模板路径"
                  v-model:value="form.template"
                />
              </a-form-item>

              <a-form-item label="文章类型" name="type">
                <a-radio-group v-model:value="form.type" @change="onTypeChange">
                  <a-radio :value="0">文章</a-radio>
                  <a-radio :value="1">外链</a-radio>
                  <a-radio :value="2">图集</a-radio>
                </a-radio-group>
              </a-form-item>
            </a-col>
          </a-row>
          <a-row :gutter="16">
            <a-col :span="12">
              <a-form-item label="关键字" name="keywords">
                <a-input
                  allow-clear
                  placeholder="请输入关键字"
                  v-model:value="form.keywords"
                />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="发布时间" name="createTime">
                <a-date-picker
                  show-time
                  format="YYYY-MM-DD HH:mm:ss"
                  placeholder="请选择发布时间"
                  v-model:value="form.createTime"
                />
              </a-form-item>
            </a-col>
          </a-row>
          <a-row>
            <a-col :span="24">
              <a-form-item
                label="图片"
                name="image"
                :label-col="{ flex: '90px' }"
                :wrapper-col="{ flex: '1' }"
              >
                <ele-image-upload
                  v-model:value="images"
                  :drag="true"
                  :multiple="true"
                  :upload-handler="uploadHandler"
                  :remove-handler="removeHandler"
                  @upload="onUpload"
                />
              </a-form-item>
            </a-col>
          </a-row>
          <a-row :gutter="16" v-if="form.type === 1">
            <a-col :span="24">
              <a-form-item
                label="外链地址"
                :label-col="{ flex: '90px' }"
                :wrapper-col="{ flex: 1 }"
              >
                <a-input
                  allow-clear
                  :disabled="form.type !== 1"
                  placeholder="请输入外链地址"
                  v-model:value="form.link"
                />
              </a-form-item>
            </a-col>
          </a-row>
          <a-row :gutter="16">
            <a-col :span="24">
              <a-form-item
                label="文章描述"
                :label-col="{ flex: '90px' }"
                :wrapper-col="{ flex: '1' }"
              >
                <a-textarea
                  :rows="4"
                  :maxlength="200"
                  placeholder="请输入文章描述"
                  v-model:value="form.summary"
                />
              </a-form-item>
            </a-col>
          </a-row>
        </a-col>
        <a-col :span="12">
          <a-row :gutter="16" v-if="form.type === 0">
            <a-col :span="24">
              <a-form-item
                label="内容"
                :label-col="{ flex: '60px' }"
                :wrapper-col="{ flex: '1' }"
                name="review"
              >
                <tinymce-editor v-model:value="form.content" :init="config" />
              </a-form-item>
            </a-col>
          </a-row>
        </a-col>
      </a-row>
    </a-form>
  </ele-modal>
</template>

<script lang="ts" setup>
  import { ref, reactive, watch } from 'vue';
  import { message } from 'ant-design-vue/es';
  import type { FormInstance, Rule } from 'ant-design-vue/es/form';
  import { storeToRefs } from 'pinia';
  import { useThemeStore } from '@/store/modules/theme';
  import useFormData from '@/utils/use-form-data';
  import type { ItemType } from 'ele-admin-pro/es/ele-image-upload/types';
  import CateSelect from './cate-select.vue';
  import type { Article } from '@/api/content/article/model';
  import { addArticle, updateArticle } from '@/api/content/article';
  import request from '@/utils/request';
  import type { Category } from '@/api/content/category/model';
  import TinymceEditor from '@/components/TinymceEditor/index.vue';
  import dayjs from 'dayjs';

  // 是否开启响应式布局
  const themeStore = useThemeStore();
  const { styleResponsive } = storeToRefs(themeStore);

  const emit = defineEmits<{
    (e: 'done'): void;
    (e: 'update:visible', visible: boolean): void;
  }>();

  const props = defineProps<{
    // 弹窗是否打开
    visible: boolean;
    // 修改回显的数据
    data?: Article | null;
    // 全部栏目
    cateList: Category[];
    // 栏目id
    cateId?: number;
  }>();

  //
  const formRef = ref<FormInstance | null>(null);
  const editorRef = ref<InstanceType<typeof TinymceEditor> | null>(null);
  // 是否是修改
  const isUpdate = ref(false);

  // 提交状态
  const loading = ref(false);

  // 标题图
  const images = ref<ItemType[]>([]);

  const config = ref({
    height: 280,
    menubar: false,
    images_upload_handler: (blobInfo, success, error) => {
      const file = blobInfo.blob();
      // 使用 axios 上传，实际开发这段建议写在 api 中再调用 api
      const formData = new FormData();
      formData.append('file', file, file.name);
      request
        .post('/file/upload', formData)
        .then((res) => {
          if (res.data.code === 0) {
            success(res.data.data);
          } else {
            error(res.data.message);
          }
        })
        .catch((e) => {
          console.error(e);
          error(e.message);
        });
    },
    // 自定义文件上传(这里使用把选择的文件转成 blob 演示)
    file_picker_callback: (callback: any, _value: any, meta: any) => {
      const input = document.createElement('input');
      input.setAttribute('type', 'file');
      // 设定文件可选类型
      if (meta.filetype === 'image') {
        input.setAttribute('accept', 'image/*');
      } else if (meta.filetype === 'media') {
        input.setAttribute('accept', 'video/*');
      }
      input.onchange = () => {
        const file = input.files?.[0];
        if (!file) {
          return;
        }
        if (meta.filetype === 'media') {
          if (!file.type.startsWith('video/')) {
            editorRef.value?.alert({ content: '只能选择视频文件' });
            return;
          }
        }
        if (file.size / 1024 / 1024 > 20) {
          editorRef.value?.alert({ content: '大小不能超过 20MB' });
          return;
        }
        const reader = new FileReader();
        reader.onload = (e) => {
          if (e.target?.result != null) {
            const blob = new Blob([e.target.result], { type: file.type });
            callback(URL.createObjectURL(blob));
          }
        };
        reader.readAsArrayBuffer(file);
      };
      input.click();
    }
  });
  //单选改变事件
  const onTypeChange = () => {
    if (form.type === 0) {
      form.link = '';
    }
  };
  // 表单数据
  const { form, resetFields, assignFields } = useFormData<Article>({
    id: undefined,
    cateId: undefined,
    title: '',
    user: '',
    origin: '',
    type: 0,
    link: '',
    image: '',
    keywords: '',
    template: '',
    summary: '',
    content: '',
    createTime: undefined
  });

  // 表单验证规则
  const rules = reactive<Record<string, Rule[]>>({
    title: [
      {
        required: true,
        message: '请输入标题',
        type: 'string',
        trigger: 'blur'
      }
    ]
  });
  /* 上传事件 */
  const uploadHandler = (file: File) => {
    const item: ItemType = {
      file,
      uid: (file as any).uid,
      name: file.name,
      progress: 0,
      status: undefined
    };
    if (!file.type.startsWith('image')) {
      message.error('只能选择图片');
      return;
    }
    if (file.size / 1024 / 1024 > 2) {
      message.error('大小不能超过 2MB');
      return;
    }
    item.url = window.URL.createObjectURL(file);
    images.value.push(item);
    onUpload(item);
  };

  const removeHandler = (item) => {
    images.value = images.value.filter((d) => d !== item);
  };

  /* 上传 item */
  const onUpload = (d: ItemType) => {
    const item: any = images.value.find((t) => t.uid === d.uid) ?? d;
    // 上传
    item.status = 'uploading';
    const formData = new FormData();
    formData.append('file', item.file);
    request({
      url: '/file/upload',
      method: 'post',
      data: formData,
      onUploadProgress: (e: any) => {
        // 文件上传进度回调
        if (e.lengthComputable) {
          item.progress = (e.loaded / e.total) * 100;
        }
      }
    })
      .then((res) => {
        if (res.data.code === 0) {
          item.status = 'done';
          item.url = res.data.data;
        }
      })
      .catch((e) => {
        message.error(e);
        item.status = 'exception';
      });
  };
  /* 保存编辑 */
  const save = () => {
    if (!formRef.value) {
      return;
    }
    formRef.value
      .validate()
      .then(() => {
        loading.value = true;
        let img_arr = [];
        if (images.value.length > 0) {
          images.value.forEach((item: any) => {
            img_arr.push(item.url);
          });
        }
        const articleForm = {
          ...form,
          createTime: dayjs(form.createTime).format('YY-MM-DD HH:mm:ss'),
          image: JSON.stringify(img_arr)
        };
        const saveOrUpdate = isUpdate.value ? updateArticle : addArticle;
        saveOrUpdate(articleForm)
          .then((msg) => {
            loading.value = false;
            message.success(msg);
            updateVisible(false);
            emit('done');
          })
          .catch((e) => {
            loading.value = false;
            message.error(e.message);
          });
      })
      .catch(() => {});
  };

  /* 更新visible */
  const updateVisible = (value: boolean) => {
    emit('update:visible', value);
  };

  watch(
    () => props.visible,
    (visible) => {
      if (visible) {
        if (props.data) {
          if (props.data.image != undefined) {
            let img_arr = JSON.parse(props.data.image);
            img_arr.map((item, uid) => {
              images.value.push({
                uid: uid,
                url: item
              });
            });
          }
          assignFields({
            ...props.data,
            createTime: dayjs(props.data.createTime, 'YY-MM-DD HH:mm:ss')
          });
          isUpdate.value = true;
        } else {
          form.cateId = props.cateId;
          isUpdate.value = false;
        }
      } else {
        resetFields();
        images.value = [];
        formRef.value?.clearValidate();
      }
    }
  );
</script>
